import React from 'react'

import '../css/work.css'
import eventEmitter from '../event'

class Work extends React.Component{
    constructor(props){
        super(props)
        this.state={
            list:[],
        }
        this.change=(item,index)=>{
            item.status=1

            //发送改变后的元素
            let obj=item
            eventEmitter.emit('sendToFinish',obj)

            this.state.list.splice(index,1)
            this.setState({
                list:this.state.list
            })
            // console.log(this.state.list);
        }
        this.del=(item,index)=>{
            this.state.list.splice(index,1)
            this.setState({
                list:this.state.list
            })
        }
        this.update=(item,index)=>{
            let newCon=prompt('请输入要修改的内容')
            item.content=newCon
            this.state.list.splice(index,1,item)
            this.setState({
                list:this.state.list
            })
        }
    }
    componentDidMount(){
        console.log(JSON.parse(localStorage.getItem('list')));
        //组件完成挂载后就绑定事件
        eventEmitter.addListener('sendObj',(obj)=>{
            // console.log(obj);
            // console.log(this.state);
            this.state.list.push(obj)
            this.setState({     //语法必须是this.serState({}),方法带()
                list:this.state.list
            })
            localStorage.setItem('list',JSON.stringify(this.state.list))
            console.log(localStorage.getItem('list'));
            // console.log(this.state.list);
        })
        eventEmitter.addListener('sendToWork',(obj)=>{
            this.state.list.push(obj)
            this.setState({
                list:this.state.list
            })
        })
    }
    render(){
        return(
            <div className='work'>
                <h1><b>正在进行{this.state.list}</b> <span>{this.state.list.length}</span></h1>
                <ul>
                    {
                        this.state.list.map((item,index)=>{
                                return <li key={index}>
                                <input type="checkbox" onChange={()=>{this.change(item,index)}} checked={item.status==1} />
                                <p>{item.content}</p>
                                <button onClick={()=>{this.update(item,index)}}>改</button>
                                <span onClick={()=>{this.del(item,index)}}>-</span>
                                </li>
                        })
                    }

                </ul>
            </div>
        )
    }
}

export default Work;